#-*- coding:utf-8 -*-

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import os
from vno import *
from vno_path import *
from vno_data import *

mpl.rcParams['axes.unicode_minus']=False
# 不显示图例
mpl.rcParams['legend.frameon']=False
# 定义中文字体
ch_font=mpl.font_manager.FontProperties(fname='simhei.ttf')
def creat_dir(dirs):
    if not os.path.exists(dirs):
        os.makedirs(dirs)

def plot2(datas, out_dir, file_name, accuracy):
    edge_id = datas[:,0]
    edge_id_hat= datas[:,1]
    edge_r = datas[:,4]
    deta_r= datas[:,2] + edge_r
    deta_r_hat = datas[:,3] + edge_r
    x = range(1, len(edge_id)+1)
    plt.figure(figsize=(12,4.8))
    plt.subplots_adjust(wspace=0.1)
    plt.subplot(1,2,1)
    title = file_name + u'预测结果'
    plt.suptitle(title,fontproperties=ch_font)
    plt.plot(x,edge_id,'+',color='b',label = u'原始编号')
    # markeredgecolor是控制圆圈的边缘颜色，markerfacecolor是控制圆心的颜色，'none'就是空心
    plt.plot(x,edge_id_hat,'o',markerfacecolor='none',  markeredgecolor = 'r', label = u'预测编号')
    title = file_name + u'准确率:'+ accuracy[0]
    plt.title(title,fontproperties=ch_font)
    # plt.text(len(x_train)*0.4, 10, u'准确率:'+ accuracy[0], fontproperties=ch_font)
    # plt.yticks(np.arange(min(y_train),max(y_train)+1))
    plt.xlabel(u'样本序列', fontproperties=ch_font)
    plt.ylabel(u'分支编号', fontproperties = ch_font)
    plt.legend(frameon = True, loc = 'best', prop = ch_font)

    plt.subplot(1,2,2)
    plt.plot(x,deta_r,'b-',label = u'故障风阻')
    plt.plot(x,edge_r,'k-',label = u'原始风阻')
    plt.plot(x,deta_r_hat,'r-',markerfacecolor='none',  markeredgecolor = 'r', label = u'预测风阻')
    title = file_name + u'差值小于0.1的准确率:'+ accuracy[1]
    plt.title(title,fontproperties=ch_font)
    # plt.text(len(x_test)*0.4, 10, u'准确率:'+ accuracy[1], fontproperties=ch_font)
    # plt.yticks(np.arange(min(y_test_hat),max(y_test_hat)+1))
    plt.xlabel(u'样本序列', fontproperties=ch_font)
    # plt.ylabel(u'故障分支', fontproperties = ch_font)
    # 设置图例
    plt.legend(frameon = True, loc = 'best', prop = ch_font)
    plt.savefig(out_dir+file_name + u'结果.svg',format='svg',dpi=300)
    # plt.show()
    plt.close()

def plotting(out_ret,edge_r,edge_ids):
    # out_ret = [[9,9,0.539,0.557],[8,8,-0.404,-0.426],[2,2,1.157,1.179],[6,6,0.484,0.463],[7,5,-0.016,0.013],[5,5,1.221,0.810],[3,3,0.747,0.786],[4,5,0.020,-0.348]]
    plot_dir = './out/plots/'
    creat_dir(plot_dir)
    min_value = 0.1
    # sorted_ret = out_ret
    # sorted_ret.sort(key=sortListByOne)
    ds = np.array(out_ret)
    edges_r = [edge_r[int(d[0])-1] for d in out_ret]
    datas = np.c_[ds,np.array(edges_r).T]

    right_hat = [rh for rh in out_ret if rh[0] == rh[1]]
    accuracy1 = '%.2f%%'%(1.0*len(right_hat)/len(datas)*100)
    right_hat2 = [rh for rh in out_ret if abs(rh[2] - rh[3]) < min_value]
    accuracy2 = '%.2f%%'%(1.0*len(right_hat2)/len(datas)*100)
    accuracy = []
    accuracy.append(accuracy1)
    accuracy.append(accuracy2)    
    # sorted_datas = np.array(sorted_ret)
    plot2(datas,plot_dir,u'全部分支',accuracy)
    # edge_num = len(set(datas[:,0].tolist()))
    for i in edge_ids:
        y = [d for d in out_ret if d[0]==i]
        edges_r = [edge_r[i-1] for d in out_ret if d[0]==i]
        ds = np.array(y)
        if len(ds) <= 0:
            continue
        datas = np.c_[ds,np.array(edges_r).T]
        right_hat = [rh for rh in y if rh[0] == rh[1]]
        accuracy1 = '%.2f%%'%(1.0*len(right_hat)/len(datas)*100)
        right_hat2 = [rh for rh in y if abs(rh[2] - rh[3]) < min_value]
        accuracy2 = '%.2f%%'%(1.0*len(right_hat2)/len(datas)*100)
        accuracy = []
        accuracy.append(accuracy1)
        accuracy.append(accuracy2)    
        plot2(datas,plot_dir,'e%d'%i,accuracy)

def plot(datas, out_dir, file_name):
    edge_id = datas[:,0]
    edge_id_hat= datas[:,1]
    deta_r= datas[:,2]
    deta_r_hat = datas[:,3]
    x = range(1, len(edge_id)+1)
    plt.figure(figsize=(12,4.8))
    plt.subplots_adjust(wspace=0.1)
    plt.subplot(1,2,1)
    title = file_name + u'预测结果'
    plt.suptitle(title,fontproperties=ch_font)
    plt.plot(x,edge_id,'+',color='b',label = u'原始编号')
    # markeredgecolor是控制圆圈的边缘颜色，markerfacecolor是控制圆心的颜色，'none'就是空心
    plt.plot(x,edge_id_hat,'o',markerfacecolor='none',  markeredgecolor = 'r', label = u'预测编号')
    title = file_name + u'错误预测情况'
    plt.title(title,fontproperties=ch_font)
    plt.xlabel(u'样本序列', fontproperties=ch_font)
    plt.ylabel(u'分支编号', fontproperties = ch_font)
    plt.legend(frameon = True, loc = 'best', prop = ch_font)

    plt.subplot(1,2,2)
    plt.plot(edge_id_hat,abs(deta_r-deta_r_hat),'r+',label = u'风阻差值')
    title = file_name + u'错误预测差值'
    plt.title(title,fontproperties=ch_font)
    # plt.text(len(x_test)*0.4, 10, u'准确率:'+ accuracy[1], fontproperties=ch_font)
    # plt.yticks(np.arange(min(y_test_hat),max(y_test_hat)+1))
    plt.xlabel(u'错误分支编号', fontproperties=ch_font)
    # plt.ylabel(u'故障分支', fontproperties = ch_font)
    # 设置图例
    plt.legend(frameon = True, loc = 'best', prop = ch_font)
    plt.savefig(out_dir+file_name + u'错误预测结果.tif',dpi=300)
    # plt.show()
    plt.close()

def plot_erro(out_ret,edge_r,edge_ids):
    plot_dir = './out/plots/'
    creat_dir(plot_dir)
    min_value = 0.1
    ds = np.array(out_ret)

    erro_hat = [eh.tolist() for eh in ds if int(eh[0]) != int(eh[1])]
    datas = np.array(erro_hat)
    if len(datas) > 0:
        hat_list = datas[:,1].tolist()
        for i in set(hat_list): 
            print(u'分支{0}的个数占的比例为：{1}%'.format(i,hat_list.count(i)*100.0/len(hat_list))) 
        plot(datas,plot_dir,u'全部分支')
    for i in edge_ids:
        y = [d for d in out_ret if d[0]==i]
        ds = np.array(y)
        erro_hat = [eh.tolist() for eh in ds if int(eh[0]) != int(eh[1])]
        datas = np.array(erro_hat)
        if len(datas) <= 0:
            continue
        plot(datas,plot_dir,'e%d'%i)

def creat_plot(file_name):
    out_ret = np.loadtxt(file_name,dtype=None,skiprows=1)
    ga_config = read_json_file(GA_CONFIG_FILE)
    graph_datas = read_graph_datas(ga_config['graph_datas'])    
    edges = graph_datas['edges']
    shaft_ids = graph_datas['shaft_eID']
    ids = [int(ee['id']) for ee in edges if not is_zero_edge(ee)]
    edge_ids = [e_id for e_id in ids if e_id not in shaft_ids]
    edge_r = [ee['r'] for ee in edges if not is_zero_edge(ee)]
    plotting(out_ret,edge_r,edge_ids)
    plot_erro(out_ret,edge_r,edge_ids)

if __name__ == "__main__":
    creat_plot("./out/out_ret.txt")